import Vue from 'vue'
import VueRouter from 'vue-router'
// 解决重复点击报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch(err => {})
};
Vue.use(VueRouter)

const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: "/home"
  },
  {
    // 首页路由
    path: '/home',
    name: 'home',
    meta: {
      isTabShow: true,
      num: 0
    },
    component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue'),
    children: [
      {
        path: "/home/searchPopup",
        name: "searchPopup",
        component: () => import(/* webpackChunkName: "searchPopup" */ '../views/searchPopup.vue')
      }
    ]
  },
  // 分类的搜索
  {
    path: "/home/searchPopup",
    name: "searchPopup1",
    component: () => import(/* webpackChunkName: "searchPopup1" */ '../views/searchPopup.vue')
  },
  {
    // 专题路由
    path: "/topic",
    name: "topic",
    meta: {
      isTabShow: true,
      num: 1
    },
    component: () => import(/*webpackChunkName: "topic" */ '../views/topic.vue')
  },
  {
    // 分类路由
    path: "/type",
    name: "type",
    meta: {
      isTabShow: true,
      num: 2
    },
    component: () => import(/*webpackChunkName: "type" */ '../views/type.vue')
  },
  {
    // 购物车路由
    path: "/cart",
    name: "cart",
    meta: {
      isTabShow: true,
      num: 3
    },
    component: () => import(/*webpackChunkName: "cart" */ '../views/cart.vue')
  },
  {
    // 我的路由
    path: "/user",
    name: "user",
    meta: {
      isTabShow: true,
      num: 4
    },
    component: () => import(/*webpackChunkName: "user" */ '../views/user.vue')
  },
  {
    // 首页的分类页
    path: "/channer",
    name: "channer",
    component: () => import(/*webpackChunkName: "channer" */ '../views/channer.vue')
  },
  {
    // 首页的分类页
    path: "/detail/:id",
    name: "detail",
    component: () => import(/*webpackChunkName: "detail" */ '../views/detail.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


/* 
  路由守卫：

*/
router.beforeEach((to, from, next) => {
  /* 
  to  你要去的路由(你去哪？)
  from    你从哪里俩
  例如：  /home => /cart
  next  是一个函数，表示下一步

  例如  
      首页 /home  ->  购物车 /cart
      首页 /home ->  分类 /type
  */
// console.log(to);
// console.log(from);
// next()

  if (to.path == "/cart") {
    // 判断token
    // 模拟token  如果为false，就是当前没有登录，如果为true，就是当前登录了
    let token = localStorage.getItem('token');
    if (token) {
      // 有token，想去哪个页面都行
      next()
    } else {
      // 没有token，不允许查看购物车页，强制跳到/user 去登录
      next("/user")
    }
  }else{
    next()
  }
})
export default router
